<?php

namespace App\Exports;

use App\Models\PassLog;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;


class PassLogExport implements FromCollection,WithHeadings,WithMapping
{
    /**
    * @return \Illuminate\Support\Collection
    */

    public function collection()
    {
        $query=PassLog::query()->with(['user','housings','housingsorder','equipments']);
        if (isset($this->filters['ids'])) {
            $query->whereIn('id', explode(',',$this->filters['ids']));
        }
        return $query->get();
    }

    public function headings(): array
    {
        return [
            '房源码',
            '房屋地址',
            '门锁ID',
            '开门人姓名',
            '人员类型',
            '开门人电话',
            '通行时间',
            '排房订单号',
            // ... 其他列标题
        ];
    }

    public function map($passlog): array
    {
        // 假设订单有 id 和 total 字段
        $orderData[] = [
            $passlog['housings_num']=>isset($passlog['housings']['housings_num']) ? $passlog['housings']['housings_num'] :'',
            $passlog['hou_address']=isset($passlog['housings']['hou_address']) ? $passlog['housings']['hou_address'] :'',
            $passlog['equipments_id'],
            $passlog['real_name']=isset($passlog['user']['real_name']) ? $passlog['user']['real_name'] :'',
            $passlog['type']=isset($passlog['user']['type']) ? $passlog['user']['type'] :'',
            $passlog['phone_number']=isset($passlog['user']['phone_number']) ? $passlog['user']['phone_number'] :"",
            $passlog['enter_at'],
            $passlog['sn']=isset($passlog['housingsorder']['sn']) ? $passlog['housingsorder']['sn'] :"",

        ];
        // 展开订单数据，以便每行都有用户信息和对应的订单信息
        return array_merge(...$orderData);
    }
}
